<?php

namespace App\Http\Controllers\Home;

use App\Model\Manager;
use App\Model\Permission;
use App\Model\Permission_role;
use App\Model\Role;
use App\Model\Role_user;
use App\Model\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Keling\Menu\Repositories\MenuRepository;
use League\Flysystem\Exception;
use Zizaco\Entrust\Entrust;
//账号角色管理
class ManagerController extends CommonController
{
    //
	protected $model;
	protected $permission_role;
	protected $role_user;
	protected $permission;
	protected $roles;
	protected $menuRepository;
	protected $Users;
	public function __construct(MenuRepository $menuRepository)
	{
		parent::__construct();
		$this->model=new Users();
		$this->permission_role=new Permission_role();
		$this->role_user=new Role_user();
		$this->permission=new Permission();
		$this->roles=new Role();
		$this->menuRepository = $menuRepository;
		$this->Permission=new Permission();
		$this->Users=new Users();
	}


//	角色列表
	public function role_list(Request $request){
		$where=[];
		$where['company_id']=$this->company_id;
		$where['status']=isset($request->status)?$request->status:null;
		$where['display_name']=isset($request->display_name)?$request->display_name:null;

		$allRoleData=$this->roles->all_role($where);
		foreach($allRoleData as $kk=>$vv){
			$allRoleData[$kk]['status']=$allRoleData[$kk]['status']==1?'有效':'失效';
		}
		return $allRoleData;
	}
//	账号列表
	public function manager_list(Request $request){
		$where=[];
		$where['company_id']=$this->company_id;
		$where['status']=isset($request->status)?$request->status:null;
		$where['name']=isset($request->name)?$request->name:null;
		$userData=$this->model->alluser($where)->toArray();
		foreach ($userData as $kk=>$vv){
			$userData[$kk]['name']=$vv['phone'];
			$userData[$kk]['status']=$userData[$kk]['status']==1?'有效':'失效';
		}
		return $userData;
	}


	public function user_list(Request $request){
		try{
			$data=$this->model->where(['status'=>1,'company_id'=>$this->company_id])->get();
		}catch (\Exception $exception){
			$message=$exception->getMessage();
		}
		if(!isset($message)){
			return $this->success($data);
		}else{
			return $this->failed($message);
		}
	}


//	添加账号
	public function add_manager(Request $request){
		$data=$request->only($this->model->getFillable());
		$data['password']=bcrypt($data['password']);
		$data['company_id']=$this->company_id;
		try{
			$result=$this->model->create($data);
		}catch(\Exception $exception){
			$message=$exception->getMessage();
		}
		if(!isset($message)){
			$this->stored($result);
		}else{
			$this->failed($message);
		}
		return $data;
	}

//	删除账号
	public function del_manager(Request $request){
		$id=$request->id;
		try{
			$result=$this->model->where(['id'=>$id])->update(['status'=>0]);
		}catch (\Exception $exception){
			$message=$exception->getMessage();
		}
		if(!isset($message)){
			return $this->updated($result);
		}else{
			return $this->failed($message);
		}
	}

//	账号已配置角色
	public function manage_role_list(Request $request){
		$uid=$request->uid;
		$data=$this->role_user->allRoles($uid);
		$newArr=[];
		foreach($data as $kk=>$vv){
			$newArr[$kk]['id']=$vv['role_id'];
			$newArr[$kk]['name']=$vv->roles->name;
			$newArr[$kk]['display_name']=$vv->roles->display_name;
			$newArr[$kk]['created_at']=$vv->roles->created_at;
			$newArr[$kk]['created_at']=date("Y-m-d",strtotime($vv->roles->created_at));
		}

		return $this->success($newArr);
	}

	
//	账号未配置的角色
	public function manage_role_list_no(Request $request){
		$uid=$request->uid;
		$name=$request->display_name;
		$roles=$this->role_user->where(['user_id'=>$uid])->pluck('role_id');
		$data=$this->roles->where('display_name','like','%'.$name.'%')
			->where(['company_id'=>$this->company_id])
			->where(function ($query){
				$query->where(['parent_id'=>1])->orWhere(function ($query){
					$query->whereNull('parent_id');
				});
			})
			->whereNotIn('id',$roles)
			->get();
		$newArr=[];
		foreach($data as $kk=>$vv){
			$newArr[$kk]['id']=$vv['id'];
			$newArr[$kk]['name']=$vv['name'];
			$newArr[$kk]['display_name']=$vv['display_name'];
			$newArr[$kk]['create_time']=date("Y-m-d",strtotime($vv['create_time']));
		}
		return $newArr;
	}
	
//	给账号取消角色配置
	public function manage_role_del(Request $request){
//		模拟数据
//		$data=[
//			'uid'=>7,
//			'role_id'=>[5],
//		];
		$data=$request->input();
		DB::beginTransaction();
		try{
			$result=$this->role_user->where(['user_id'=>$data['uid']])->whereIn('role_id',$data['role_id'])->delete();
			DB::commit();
		}catch (\Exception $exception){
			$message=$exception->getMessage();
			DB::rollBack();
		}
		if(!isset($message)){
			return $this->updated([]);
		}else{
			return $this->failed($message);
		}

	}
//	给账号配置角色
	public function assign_role(Request $request){
//		模拟数据
//		$data=[
//			'uid'=>1,
//			'roleData'=>[1,2,3]
//		];
//		模拟数据结束
		$data=$request->input();
		$uid=$data['uid'];
		$roleData=$data['roleData'];
		$newArray=[];
		foreach ($roleData as $k=>$v){
			$newArray[$k]['user_id']=$uid;
			$newArray[$k]['role_id']=$v;
		}
//		return $newArray;
		DB::beginTransaction();
		try{
			$result=DB::table('role_user')->insert($newArray);
			DB::commit();
		}catch (\Exception $exception){
			$message=$exception->getMessage();
			DB::rollBack();
		}
		if(!isset($message)){
			return $this->stored($result);
		}else{
			return $this->failed($message);
		}

	}
//	创建角色
	public function add_Role(){
		$user_id=Auth::user()->id;
		$result=$this->role_user->where(['user_id'=>$user_id,'role_id'=>1])->first();
		if($result){
			return $this->success(['status'=>1,'message'=>'显示']);
		}
		return $this->success(['status'=>0,'message'=>'不显示']);

	}
//	创建保存角色
	public function addRole(Request $request){
		$user_id=Auth::user()->id;
//		是否是超级管理员
		$administrator=isset($request->administrator)?$request->administrator:null;
		if($administrator){
			$parent_id=1;
		}else{
			$parent_id=null;
		}
		$owner = new Role();
		DB::beginTransaction();
		try{
			$data['name'] =date("YmdHis",time());
			$data['company_id']=isset($request->company_id)?$request->company_id:$this->company_id;
			$data['display_name']=$request->display_name;
			$data['user_id']=$user_id;
			$data['parent_id']=$parent_id;
			$result=$owner->create($data);
			if($parent_id){
				 $this->createPermission($result->id);
			}
			DB::commit();
		}catch(\Exception $exception){
			$message=$exception->getMessage();
			DB::rollBack();
		}
			if(!isset($message)){
				return $this->stored($result);
			}else{
				return $this->failed($message);
			}
	}
//	编辑角色
	public function editRole(Request $request){
		try{
			$result=$this->roles->where(['id'=>$request->id])->first();
		}catch(\Exception $exception){

		}
		if(!isset($message)){
			return $this->success($result);
		}else{
			return $this->failed($message);
		}
	}
//	编辑保存角色
	public function saveRole(Request $request){
		$user_id=Auth::user()->id;
		$owner = new Role();
		DB::beginTransaction();
		try{
			$data['company_id']=$this->company_id;
			$data['display_name']=$request->display_name;
			$result=$owner->where(['id'=>$request->id])->update($data);
			DB::commit();
		}catch(\Exception $exception){
			$message=$exception->getMessage();
			DB::rollBack();
		}
		if(!isset($message)){
			return $this->updated(['code'=>200,'message'=>'更新成功']);
		}else{
			return $this->failed($message);
		}
	}

//	编辑角色有效无效
	public function edit_status(Request $request){
		try{
			$result=Role::where(['id'=>$request->id])->update(['status'=>$request->status]);
		}catch (\Exception $exception){
			$message=$exception->getMessage();
		}
		if(!isset($message)){
			return $this->updated($result);
		}else{
			return $this->failed($message);
		}
	}


//	获取角色已配置的权限列表
	public function all_role_configured(Request $request){
		$data=$this->roles->all_role_configured($request->role_id)->permission_role;
		$newArr=[];
		foreach($data as $kk=>$vv){
			$newArr[$kk]['id']=$vv['permission']['id'];
			$newArr[$kk]['name']=$vv['permission']['name'];
			$newArr[$kk]['menu_name']=$vv['permission']['menu_name'];
			$newArr[$kk]['created_at']=date("Y-m-d",strtotime($vv['permission']['created_at']));
		}
		return  $this->success($newArr);
	}
//	给角色添加权限
	public function role_permission(Request $request){
//		$permission_role=$this->permission_role;
//		模拟数据
//		$data=[
//			'role_id'=>1,
//			'permission'=>[4,5,6],
//		];
//		模拟数据结束
		$data=$request->input();
		$role_id=$data['role_id'];
		$permission=$data['permission'];

		$newarray=[];
		foreach($permission as $kk=>$vv){
			$newarray[$kk]['role_id']=$role_id;
			$newarray[$kk]['permission_id']=$vv;
		}
		DB::beginTransaction();
		try{
			$result=DB::table('permission_role')->insert($newarray);
			DB::commit();
		}catch (\Exception $exception){
			DB::rollBack();
			$message=$exception->getMessage();
		}
		if(!isset($message)){
			return $this->stored($result);
		}else{
			return $this->failed($message);
		}

	}

//	角色取消授权
	public function role_permission_del(Request $request){
//		模拟数据
//		$data=[
//			'role_id'=>1,
//			'permission'=>[4],
//		];
//		模拟数据结束
		$data=$request->input();
		$role_id=$data['role_id'];
		$permission=$data['permission'];
		DB::beginTransaction();
		try{
			$result=$this->permission_role->where(['role_id'=>$role_id])->whereIn('permission_id',$permission)->delete();
			DB::commit();
		}catch (\Exception $exception){
			$message=$exception->getMessage();
			DB::rollBack();
		}
		if(!isset($message)){
			return $this->updated([]);
		}else{
			return $this->failed($message);
		}

	}



//	获取角色未授权栏目
	public function permission_list(Request $request){
		$permission=$this->permission_role->where(['role_id'=>$request->role_id])->pluck('permission_id');
		$menu_name=$request->menu_name;
		$role_id=$request->role_id;
		$data=$this->permission->where('menu_name','like','%'.$menu_name.'%')
			->whereNotIn('id',$permission)
			->get();
		$newArr=[];
		foreach($data as $kk=>$vv){
			$newArr[$kk]['id']=$vv['id'];
			$newArr[$kk]['name']=$vv['name'];
			$newArr[$kk]['created_at']=date("Y-m-d",strtotime($vv['created_at']));
			$newArr[$kk]['menu_name']=$vv['menu_name'];
		}
		return $this->success($newArr);
	}
//	获取用户信息
	public function profile(){
		$userData=Auth::user();
		$user_id=$userData->id;
		$roleData=$this->role_user->allRole($user_id);
		$permissionData=$this->permission_role->all_permission($roleData);
		//获取用户的菜单
		$menu=$this->permission->allmenu($permissionData);
		$newMenu=[];
		foreach ($menu as $kk=>$vv){
			$newMenu[$kk]=$vv['menu'];
		}
		$MenuData=$this->arrayPidProcess($newMenu);
		$data['userinfo']=$userData;
		$data['menu']=$MenuData;

		return $data;
	}



	public function createPermission($role_id){
		$permissions=$this->permission->pluck('id');
		$array=[];
		foreach($permissions as $key=>$value){
			$array[$key]['role_id']=$role_id;
			$array[$key]['permission_id']=$value;
		}
		return$this->permission_role->insert($array);
	}

//查询数据整理递归函数
	public function arrayPidProcess($data,$res=array(),$pid='0',$endlevel='0'){
		foreach ($data as $k => $v){
			if($v['parent_id']==$pid){
				$res[$v['id']]['name']=$v['name'];
				$res[$v['id']]['path']=$v['path'];
				$res[$v['id']]['icon']=$v['icon'];
				$res[$v['id']]['companment']=$v['companment'];
				if($endlevel!='0'){
					if($v['level']==$endlevel){
						$child=null;
					}
					else{
						$child=arrayPidProcess($data,array(),$v['id'],$endlevel);
					}
					$res[$v['id']]['child']=$child;
				}
				else{
					$child=$this->arrayPidProcess($data,array(),$v['id']);
					if($child==''||$child==null){
						$res[$v['id']]['child']=null;
					}
					else{
						$res[$v['id']]['child']=$child;
					}
				}

			}
		}
		return $res;
	}
}
